package com.ss.tmall.service.impl;

import com.ss.tmall.mapper.PropertyMapper;
import com.ss.tmall.mapper.PropertyValueMapper;
import com.ss.tmall.pojo.Product;
import com.ss.tmall.pojo.Property;
import com.ss.tmall.pojo.PropertyValue;
import com.ss.tmall.pojo.PropertyValueExample;
import com.ss.tmall.service.PropertyService;
import com.ss.tmall.service.PropertyValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: ShengShuai
 * @Description:
 * @Date: Created in 上午 11:09  2017/12/27 0027
 * @Modified By:
 */
@Service
public class PropertyValueServiceImpl implements PropertyValueService {
    @Autowired
    PropertyService propertyService;
    @Autowired
    PropertyValueMapper propertyValueMapper;
    @Override
    public  void  init(Product product){
        List<Property> pts =propertyService.list(product.getCid());
        for (Property p:pts) {
            PropertyValue propertyValue =get(p.getId(),product.getId());
            if (propertyValue == null) {
                propertyValue =new PropertyValue();
                propertyValue.setPid(product.getId());
                propertyValue.setPtid(p.getId());
                propertyValueMapper.insert(propertyValue);
            }
        }
    }
    @Override
    public void  update(PropertyValue propertyValue){
    propertyValueMapper.updateByPrimaryKeySelective(propertyValue);
    }
    @Override
    public PropertyValue get(int ptid,int pid){
        PropertyValueExample example =new PropertyValueExample();
        example.createCriteria().andPidEqualTo(pid).andPtidEqualTo(ptid);
        List<PropertyValue> ptv=propertyValueMapper.selectByExample(example);
        if (ptv.isEmpty()) {
            return  null;
        }return ptv.get(0);
    }
    @Override
    public List<PropertyValue> list(int pid){
        PropertyValueExample example =new PropertyValueExample();
        List<PropertyValue> result=propertyValueMapper.selectByExample(example);
        example.createCriteria().andPidEqualTo(pid);
        for (PropertyValue p:result) {
            Property property =propertyService.get(p.getPid());
            p.setProperty(property);
        }
        return  result;
    }
}
